1661A - Array Balancing - CodeForces Solution


greedy math

Please click on ads to support us..

Python Code:

def solve():
    n =int(input())
    a = list(map(int,input().split()))
    b = list(map(int,input().split()))
    sum = 0
    for i in range(len(a)):
        if a[i] > b[i]:
            b[i],a[i] = a[i],b[i]
    for i in range(len(a)-1):
        sum += abs(a[i] - a[i+1])
        sum += abs(b[i] - b[i+1])
    print(sum)
    
tst = int(input())
for i in range(tst):
    solve()

C++ Code:

#include<bits/stdc++.h>
using namespace std;
#define int long long
#define endl "\n"
#define all(x) (x).begin(),(x).end()
#define dbg(x) cout<< #x <<" : "<<(x)<<endl;
#define dbgv(v) cout<< #v <<" : ";for(auto &i:v) cout<<(i)<<" ";cout<<endl;
void solve()
// int solve()
{
    int n;cin>>n;
    vector<int> a(n);
    int ans = 0,la = -1,lb=-1;
    for(int &i:a) cin>>i;
    for(int &i:a)
    {
        int x;cin>>x;
        int mx = max(x,i);
        int mn = min(x,i);
        if(la!=-1)
        {
            ans += abs(mx - la) + abs(mn - lb);
        }
        la = mx;
        lb = mn;
    }
    cout<<ans<<endl;
}
main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int t = 1;
    cin>>t;
    while(t--)
    {
        solve();
        // cout<<solve()<<endl;
    }
    return 0;
}


Comments

Submit
0 Comments
More Questions

Teddy and Tweety
Partitioning binary strings
Special sets
Smallest chosen word
Going to office
Color the boxes
Missing numbers
Maximum sum
13 Reasons Why
Friend's Relationship
Health of a person
Divisibility
A. Movement
Numbers in a matrix
Sequences
Split houses
Divisible
Three primes
Coprimes
Cost of balloons
One String No Trouble
Help Jarvis!
Lift queries
Goki and his breakup
Ali and Helping innocent people
Book of Potion making
Duration
Birthday Party
e-maze-in
Bricks Game